var Entries = (function() {
	
	var loadEntry = function($entryTemplate, entry) {
		$entryTemplate.find(".entry_avatar_profile_link").attr("href", "http://www.wykop.pl/ludzie/" + entry.author);
		$entryTemplate.find(".entry_avatar").attr("src", entry.author_avatar);
		$entryTemplate.find(".entry_author").text(entry.author);
		$entryTemplate.find(".entry_date").attr("datetime", entry.date);
		$entryTemplate.find(".entry_link").attr("href", entry.url);
		injectEntryBody($entryTemplate, entry.body);
		Entries.loadEntryVotes($entryTemplate, {
			vote: entry.vote_count,
			voters: entry.voters
		});
		
		$entryTemplate.find(".comments").detach();
		
		if(entry.comments && entry.comments.length > 0) {
			var $comments = $("<ul/>", {class: "comments"});
			
			$.each(entry.comments, function(i, commentData) {
				$comments.append(comment(commentData));
			});
			
			$entryTemplate.append($comments);
		}
	};
	
	var loadEntryVotes = function($entryTemplate, entryVotes) {
		$entryTemplate.find(".entry_vote_count").text(entryVotes.vote);

		var $voters = $entryTemplate.find(".entry_voters");
		$voters.children().detach();
		
		$.each(entryVotes.voters, function(i, voter) {
			var $span = $("<span/>", {});
			$span.text(voter.author);
			
			$voters.append($span);
			$voters.append(" ");
		});
	};
	
	function comment(commentData) {
		var $template = EntryTemplate.comment();
		$template.html(commentData.body);
		
		return $template;
	};
	
	function injectEntryBody($entryTemplate, entryBodyText) {
		var entryBodyLength = entryBodyText.length;
		var maxTextLength = 250;
		
		if (entryBodyLength > maxTextLength) {
			$entryTemplate.find(".entry_body_short").html(entryBodyText.cut(maxTextLength));
			$entryTemplate.find(".entry_body_extend").html(entryBodyText.substring(
						entryBodyText.indexOf(" ", maxTextLength), entryBodyLength
					));
		} else {
			$entryTemplate.find(".entry_body_short").html(entryBodyText);
		}
	};
	
	return {
		loadEntry: loadEntry,
		loadEntryVotes: loadEntryVotes
	};
})();


